﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
using NhaThuocOnline.Entities;
using NhaThuocOnline.Repositories;
using NhaThuocOnline.ViewModels;

namespace NhaThuocOnline.Service
{
    public class UserInfoService
    {
        private void InsertOrUpdate(ViewModelsUserInfo user)
        {
            //Mapper.CreateMap<ViewModelsUserInfo, UserInfo>();
            var en = Mapper.Map<ViewModelsUserInfo, UserInfo>(user);
            using (UserInfoRepository repo = new UserInfoRepository())
            {              
                repo.InsertOrUpdate(en);
                repo.Save();
            }
        }
        private void Delete(int id)
        {
            using (UserInfoRepository repo = new UserInfoRepository())
            {
                repo.Delete(id);
                repo.Save();
            }
        }
        private List<ViewModelsUserInfo> GetAll()
        {
            using (UserInfoRepository repo = new UserInfoRepository())
            {
                return Mapper.Map<List<UserInfo>, List<ViewModelsUserInfo>>(repo.GetAll.ToList());
            }
        }
        private ViewModelsUserInfo GetUserInfoById(int id)
        {
            using (UserInfoRepository repo = new UserInfoRepository())
            {
                return Mapper.Map<UserInfo, ViewModelsUserInfo>(repo.GetAll.Where(bn => bn.Id == id).FirstOrDefault());
            }
        }
        private ViewModelsUserInfo GetUserInfoByEmail(string email)
        {
            try
            {
                using (UserInfoRepository repo = new UserInfoRepository())
                {
                    ViewModelsUserInfo vmUser = Mapper.Map<UserInfo, ViewModelsUserInfo>(repo.GetAll.Where(p => p.Email == email && p.Status == (int)UserInfoStatus.Active).FirstOrDefault());
                    return vmUser;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //Register a new account => Insert email, pass into the UserInfo table
        public void SignUp(ViewModelsUserInfo vmUser)
        {
            vmUser.Status = (int)UserInfoStatus.Active;
            InsertOrUpdate(vmUser);
        }
        //Check: Is email existed in UserInfo table?
        public bool IsExistedEmail (string email)
        {
            using (UserInfoRepository repo = new UserInfoRepository())
            {
                IQueryable<UserInfo> users = repo.GetAll.Where(p => p.Email == email && p.Status != (int)UserInfoStatus.Removed);
                UserInfo user = users.FirstOrDefault();
                return(user == null);
            }
        }
        


    }
}
